package com.tql.pandian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.datasource.annotation.Master;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.tql.pandian.entity.PanDianPeriodShopEntity;
import com.tql.pandian.entity.TqlPandianPeriodEntity;
import com.tql.pandian.entity.TqlPandianPeriodShopEntity;
import com.tql.pandian.entity.dto.PanDianPeriodDTO;
import com.tql.pandian.entity.dto.PeriodPcListDTO;
import com.tql.pandian.entity.dto.TqlPandianPeriodDTO;
import com.tql.pandian.entity.vo.HillKingDeeVo;
import com.tql.pandian.entity.vo.PanDianBeanVo;
import com.tql.pandian.entity.vo.PanDianListVo;
import com.tql.pandian.entity.vo.PandianVo;
import com.tql.pandian.mapper.PandianPeriodMapper;
import com.tql.pandian.mapper.PandianPeriodShopMapper;
import com.tql.pandian.service.ICommonService;
import com.tql.pandian.service.IPandianPeriodService;
import com.tql.pandian.service.IPandianPeriodShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.utils.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PandianPeriodService implements IPandianPeriodService {
    @Autowired
    private PandianPeriodMapper pandianPeriodMapper;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private PandianPeriodShopMapper pandianPeriodShopMapper;

    @Autowired
    private IPandianPeriodShopService pandianPeriodShopService;

    @Override
    public List<PandianVo> queryList(TqlPandianPeriodShopEntity entity) {
        return pandianPeriodMapper.selectPanDianList(entity.getDeptCode());
    }

    @Override
    public List<Map> queryPcList(PeriodPcListDTO dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        PageInfo pageInfo = new PageInfo(pandianPeriodMapper.selectPcList(dto));
        return pageInfo.getList();
    }

    public List<Map> queryPcList1(PeriodPcListDTO dto) {
      return pandianPeriodMapper.selectPcList(dto);
    }

    @Override
    public Integer queryPcListCount(PeriodPcListDTO dto) {
        return pandianPeriodMapper.selectPcListCount(dto);
    }

    @Override
    public List<PandianVo> getTimeSlot(TqlPandianPeriodShopEntity entity) {
        return pandianPeriodMapper.selectTimeSlot(entity.getDeptCode()).stream().map(k->{
            PandianVo vo = new PandianVo();
            vo.setMonth(k.getMonth());
            vo.setEndtime(k.getMonth());
            vo.setList(k.getList());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 更新盘点
     * @param list
     * @return
     */

    @Override
    public int editPandianPeriod(List<TqlPandianPeriodEntity> list) {
        //        Date date1 = new Date(); // 创建第一个日期对象
        //        Date date2 = new Date(); // 创建第二个日期对象
        //        int result = date1.compareTo(date2); // 调用compareTo()方法进行比较
        //        if (result < 0) {
        //            System.out.println("date1 在 date2之前");
        //        } else if (result > 0) {
        //            System.out.println("date1 在 date2之后");
        //        } else {
        //            System.out.println("date1 与 date2相同");
        //        }
        int a = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getEndtime().compareTo(list.get(i).getStarttime()) < 0){
                continue;
            }
            int b = 0;
            int c = 0;
            if (null != list.get(i).getId()){
                String pattern = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                String formattedDate = sdf.format(list.get(i).getEndtime());
                list.get(i).setPandianDate(formattedDate.replace("-",""));
                b = pandianPeriodMapper.updatePandianPeriod(list.get(i));
                //更新编码
                PanDianPeriodShopEntity entity = new PanDianPeriodShopEntity();
                entity.setPid(Math.toIntExact(list.get(i).getId()));
                entity.setPcode(list.get(i).getPandianDate());
                entity.setDel(0);
                c = pandianPeriodShopMapper.updatePanDianPeriodShopCode(entity);
            }else {
                //有添加的
                //b = this.addPanDian(new ArrayList<>(Arrays.asList(list.get(i))));
                TqlPandianPeriodEntity p = list.get(i);
                pandianPeriodMapper.insertPandianPeriod(p);
                List<HillKingDeeVo> hillKingDeeVoList = commonService.HillKingDees();
                // 没有门店信息
                if (Objects.isNull(hillKingDeeVoList)){
                    continue;
                }
                List<PanDianPeriodShopEntity> panDianPeriodShopEntityList = new ArrayList<>();
                int finalI = i;
                hillKingDeeVoList.forEach(t->{
                    PanDianPeriodShopEntity AA = new PanDianPeriodShopEntity();
                    AA.setPcode(p.getPandianDate());
                    AA.setDeptCode(t.getKingdeeDeptCode());
                    AA.setDel(0);
                    AA.setCreator(SecurityUtils.getUserId());
                    AA.setCreateBy(SecurityUtils.getUsername());
                    AA.setCreateTime(new Date());
                    AA.setFlag(0);
                    AA.setPandianCode(t.getKingdeeDeptCode()+"P"+list.get(finalI).getPandianDate()+"S"+list.get(finalI).getSeq());
                    AA.setPid(Math.toIntExact(p.getId()));
                    panDianPeriodShopEntityList.add(AA);
                });
                b = pandianPeriodShopService.batchInsert(panDianPeriodShopEntityList);
            }
            a = a+b;
        }
        return a;
    }

    /**
     * 新增盘点
     * @param list
     * @return
     */

    @Override
    public int addPanDian(List<TqlPandianPeriodEntity> list) {
        int m = 0;
        //先判断该月份是否已创建过了
        String month = list.get(0).getMonth();
        QueryWrapper<TqlPandianPeriodEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("month",month);
        Long count = pandianPeriodMapper.selectCount(wrapper);
        if (count>0){
            return m;
        }
        //判断时间节点需要连续
        List<TqlPandianPeriodEntity> list1 = list.stream().
                sorted(Comparator.comparing(TqlPandianPeriodEntity::getSeq)).
                collect(Collectors.toList());
     //需要开通的店
        List<HillKingDeeVo> hillKingDeeVoList = commonService.HillKingDees();
        if (Objects.isNull(hillKingDeeVoList))return 0;

        for (TqlPandianPeriodEntity entity : list1) {
            pandianPeriodMapper.insertPandianPeriod(entity);
            List<PanDianPeriodShopEntity> panDianPeriodShopEntityList = new ArrayList<>();
            for (HillKingDeeVo vo : hillKingDeeVoList) {
                PanDianPeriodShopEntity AA = new PanDianPeriodShopEntity();
                AA.setPcode(entity.getPandianDate());
                AA.setDeptCode(vo.getKingdeeDeptCode());
                AA.setDel(0);
                AA.setCreator(SecurityUtils.getUserId());
                AA.setCreateBy(SecurityUtils.getUsername());
                AA.setCreateTime(new Date());
                AA.setFlag(0);
                AA.setPandianCode(vo.getKingdeeDeptCode()+"P"+entity.getPandianDate()+"S"+entity.getSeq());
                AA.setPid(Math.toIntExact(entity.getId()));
                panDianPeriodShopEntityList.add(AA);
            }
            int l = pandianPeriodShopService.batchInsert(panDianPeriodShopEntityList);
            m = m +l;
        }
        return m;
    }

    /**
     * 查看盘点列表
     * @param pcode
     * @return
     */
    @Override
    public List<TqlPandianPeriodEntity> editMainPanDian(String pcode) {
        TqlPandianPeriodDTO tqlPandianPeriodDTO = new TqlPandianPeriodDTO();
        tqlPandianPeriodDTO.setMonth(pcode);
        return pandianPeriodMapper.selectPanDianPeriod(tqlPandianPeriodDTO);
    }

    @Override
    public List<PanDianListVo> queryPanDianPeriod(PanDianPeriodDTO panDianPeriodDTO) {
        return pandianPeriodMapper.selectPanDianPeriodByCode(panDianPeriodDTO);
    }

    /**
     * 删除盘点日期
     * @param pcode
     * @return
     */
    @Master
    @Override
    public int delMainPanDian(String pcode) {
        List<TqlPandianPeriodEntity> tqlPandianPeriodEntityList = this.editMainPanDian(pcode);
        List<Long> ids = new ArrayList<>();
        tqlPandianPeriodEntityList.forEach(t->{
            if (t.getEndtime().compareTo(new Date()) > 0){
                ids.add(t.getId());
            }
        });
        if (ids.size() >0 ){
            int a = pandianPeriodShopMapper.deleteBatchByIds(ids);
            int b = pandianPeriodMapper.deleteBatchByIds(ids);
            return a+b;
        }else {
            return 0;
        }
    }

    @Master
    @Override
    public List<PanDianBeanVo> editAssociationPanDian(String pcode) {
        List<PanDianBeanVo> list = new ArrayList<>();
        List<TqlPandianPeriodEntity> tqlPandianPeriodEntityList =  editMainPanDian(pcode);
        tqlPandianPeriodEntityList.forEach(t->{
            PanDianBeanVo panDianBeanVo = new PanDianBeanVo();
            panDianBeanVo.setId(t.getId());
            panDianBeanVo.setSeq(t.getSeq());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String startDate = dateFormat.format(t.getStarttime());
            String endDate = dateFormat.format(t.getEndtime());
            panDianBeanVo.setMothDay(startDate.substring(startDate.length()-2)+"-"+endDate.substring(endDate.length()-2));
            list.add(panDianBeanVo);
        });
        return list;
    }

    @Master
    @Override
    public int editAssociationConfirmPanDian(Long id) {
        PanDianPeriodShopEntity entity = new PanDianPeriodShopEntity();
        entity.setFlag(1);
        entity.setId(id);
        /*LoginUser loginUser= SecurityUtils.getLoginUser();
        Long userId=loginUser.getUserid();
        boolean flag=SecurityUtils.isAdmin(userId);
        if (!flag){
            String deptCode=commonService.findShopDeptCodeByUserId(userId);
            if (StringUtils.isNotEmpty(deptCode)){
                entity.setDeptCode(deptCode);
            }
        }*/
        return pandianPeriodShopService.updatePanDianPeriodShop(entity);
    }

}
